#include "main.h"

int extrFile (FILE * fileToWrite, fileHead * list,FILE * arc)
{
	char * buf = (char*) calloc (SIZE_T_8,sizeof(char));
	unsigned long long int num = 0;
	unsigned long long int sizeFileSz = 0;
	FILE * tmp_dec = NULL;
	int i = 0;
	int rc = 0;
	if (!buf)	cl_exit (EXTR_FILE_KER,MEMORY_ERR);
	envInf.buf = buf;
	fseek (arc,7,SEEK_SET);
	while ((rc = fread (buf,sizeof(char),NAME_LEN,arc)) == 1)
	{
		num = strToInt (buf,NAME_LEN);	
		if (num > SIZE_T_8)		{
			buf = (char*) calloc (num,sizeof(char));
			envInf.buf = buf;
			if (!buf) cl_exit (EXTR_FILE,MEMORY_ERR);
		}
		if ((rc = fread (buf,sizeof(char),num,arc)) != num)	{	cl_exit (EXTR_FILE_KER,READ_ERR);	}
		if ((num != list->sizeName) || (strncmp(buf,list->fileName,num)))	{	
			fseek(arc,SIZE_T_8,SEEK_CUR); //skip mtime
			if ((rc = fread (buf,sizeof(char),SIZE_T_1,arc)) != SIZE_T_1)	{	cl_exit (EXTR_FILE_KER,READ_ERR);	}
			num = strToInt (buf,SIZE_T_1); // contains huff_ubits
			if (num & LEN_8_B )	{
				if ((rc = fread (buf,sizeof(char),SIZE_T_8,arc)) != SIZE_T_8)	{	cl_exit (EXTR_FILE_KER,READ_ERR);	}
				sizeFileSz = strToInt (buf,SIZE_T_8);
			} else {
				if ((rc = fread (buf,sizeof(char),SIZE_T_4,arc)) != SIZE_T_4)	{	cl_exit (EXTR_FILE_KER,READ_ERR);	}
				sizeFileSz = strToInt (buf,SIZE_T_4);
			}
			if (!(num & NO_HUFF))	{
				fseek (arc,SIZE_T_2,SEEK_CUR);
				if (num & LEN_8_B)	{
					if ((rc = fread (buf,sizeof(char),SIZE_T_8,arc)) != SIZE_T_8)	{	cl_exit (EXTR_FILE_KER,READ_ERR);	}
					sizeFileSz = strToInt (buf,SIZE_T_8);
				}	else {
					if ((rc = fread (buf,sizeof(char),SIZE_T_4,arc)) != SIZE_T_4)	{	cl_exit (EXTR_FILE_KER,READ_ERR);	}
					sizeFileSz = strToInt (buf,SIZE_T_4);
				}
			}
			fseek (arc,sizeFileSz +4,SEEK_CUR);
		} else {	
			fseek (arc,SIZE_T_8 + SIZE_T_1,SEEK_CUR); // skip mtime and huff_ubits
			if (list->huff_ubits & LEN_8_B)	{
				fseek (arc,SIZE_T_8,SEEK_CUR);	
			}
			else {	
				fseek (arc,SIZE_T_4,SEEK_CUR);	
			}
			if (list->huff_ubits & NO_HUFF)	{
				sizeFileSz = list->fileSize;
				if ((rc = copy (arc,fileToWrite,sizeFileSz,NULL)) != 0)	{	cl_exit (EXTR_FILE_KER,COPY_ERR);	}
				fseek (arc,SIZE_T_4,SEEK_CUR);
			}
			else {
				fseek (arc,SIZE_T_2,SEEK_CUR);
				if (list->huff_ubits & LEN_8_B)
					fseek (arc,SIZE_T_8,SEEK_CUR);
				else
					fseek (arc,SIZE_T_4,SEEK_CUR);
				rc = decompres (arc,fileToWrite,list);
				fseek (arc,SIZE_T_4,SEEK_CUR);
				
				}
				//function to create huff_tree
				//function to uncoding file
				//function to copy
		}
	}
	return 0;
}
